package com.example.casper.jnuexperiment2025;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.casper.jnuexperiment2025.dataop.DataPersistence;
import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

public class BookListFragment extends Fragment {

    private BookAdapter adapter;
    private List<Book> bookList;
    private DataPersistence dataPersistence;
    private ActivityResultLauncher<Intent> activityResultLauncher;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_list, container, false);

        dataPersistence = new DataPersistence();
        bookList = dataPersistence.loadData(getContext());
        if (bookList == null || bookList.isEmpty()) {
            bookList = getListBooks(); // Load initial data if no data saved
        }
        adapter = new BookAdapter(bookList);

        RecyclerView recyclerView = view.findViewById(R.id.recycler_view_my_books);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);

        registerLauncher();
        return view;
    }

    private void registerLauncher() {
        activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                Intent data = result.getData();
                String action = data.getStringExtra("action");
                int position = data.getIntExtra("position", -1);
                String title = data.getStringExtra("book_title");
                double price = data.getDoubleExtra("book_price", 0.0);

                if ("add".equals(action) && position != -1) {
                    bookList.add(position + 1, new Book(title, R.drawable.book_no_name, price));
                    adapter.notifyItemInserted(position + 1);
                    saveData();
                } else if ("update".equals(action) && position != -1) {
                    Book bookToUpdate = bookList.get(position);
                    bookToUpdate.setTitle(title);
                    bookToUpdate.setPrice(price);
                    adapter.notifyItemChanged(position);
                    saveData();
                }
            }
        });
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        int position = adapter.getLongClickedPosition();
        Intent intent = new Intent(getContext(), BookDetailsActivity.class);
        intent.putExtra("position", position);

        switch (item.getItemId()) {
            case 0: // 添加
                intent.putExtra("action", "add");
                activityResultLauncher.launch(intent);
                break;
            case 1: // 更新
                intent.putExtra("action", "update");
                Book bookToUpdate = bookList.get(position);
                intent.putExtra("book_title", bookToUpdate.getTitle());
                intent.putExtra("book_price", bookToUpdate.getPrice());
                activityResultLauncher.launch(intent);
                break;
            case 2: // 删除
                new AlertDialog.Builder(getContext())
                        .setTitle("确认删除")
                        .setMessage("您确定要删除这本书吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            bookList.remove(position);
                            adapter.notifyItemRemoved(position);
                            saveData();
                        })
                        .setNegativeButton("取消", null)
                        .show();
                break;
        }
        return super.onContextItemSelected(item);
    }

    private void saveData() {
        dataPersistence.saveData(getContext(), bookList);
    }

    private List<Book> getListBooks() {
        List<Book> bookList = new ArrayList<>();
        bookList.add(new Book("无名之书", R.drawable.book_no_name, 29.9));
        bookList.add(new Book("软件项目管理案例教程（第3版）", R.drawable.book_2, 49.9));
        bookList.add(new Book("信息安全数学基础（第2版）", R.drawable.book_1, 39.9));
        return bookList;
    }
}